package com.zhou.utils.gaodei;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;


/**
 * @Description : 高德获取ip地址
 * @Author : zyy
 * @Date: 2024/7/16  15:10
 */
@Slf4j
public class GetIpConfig {
    private static final String url = "https://restapi.amap.com/v3/ip?key=5ced18ffb11f58eb8ecc435b9d7ca3e9&ip=111.22.16.2";
    private static final String IP = "111.22.16.2";

    /**
     * 通过ip获取地址
     * @param ip
     * @return
     */
    public static String getConfigIp(String ip) {
        log.info("开始获取地址");
        try {
            String apiUrl = url; // 替换为你的API地址
            URL url = new URL(apiUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            // 可选：设置请求头
            // connection.setRequestProperty("Header-Name", "Header-Value");

            // 获取响应码
            int responseCode = connection.getResponseCode();

            // 检查响应码是否为200（成功）
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 读取响应内容
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                // 打印结果
                System.out.println(response.toString());
                return response.toString();
            }
            log.info("获取地址结束");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "获取失败";
    }

    /**
     * 将获取出来的地址转换成map形式返回
     * @param parse
     * @return
     */
    public static Map<String, Object> getAddress(Object parse) {
        Map<String, Object> map = (Map<String, Object>) parse;
        return map;
    }


    public static void main(String[] args) {
        String configIp = getConfigIp(IP);
        Object parse = JSONObject.parse(configIp);
        System.out.println(parse);
        Map<String, Object> map = (Map<String, Object>) parse;
        System.out.println(map.get("province"));
        System.out.println(map.get("city"));
    }
}
